<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理预约项目和预约套餐</title>
    <script src="{{url_for('static', filename='js/jquery-3.6.0.min.js')}}"></script>
    <script src="{{ url_for('static', filename='js/custom_message_box.js') }}"></script>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/custom_message_box.css') }}">
    <link href="{{url_for('static', filename='css/layui.css')}}" rel="stylesheet">
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            background-color: #f9f9f9;
            margin: 20px;
            padding: 0;
            height: 800px;
            background: url("{{url_for('static', filename='img/login_admin_web.jpg')}}") no-repeat center;
            background-size: cover;
        }

        h2 {
            color: #333;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }

        table th,
        table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }


        .operation-btn {
            color: white;
            border: none;
            padding: 5px 10px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 14px;
            cursor: pointer;
        }

        .delete-btn {
            background-color: #f94646;
        }

        .add-btn {
            background-color: #1d9f1d9c;
        }

        #package-table {
            background-color: skyblue;
        }

        #item-table {
            background-color: skyblue;
        }
    </style>
    <script>
        function loadPackageDetails(packageId) {
            if (!packageId) return Promise.reject("Package ID is required.");

            return new Promise(function (resolve, reject) {
                $.ajax({
                    url: "{{ url_for('doctor.query_package_items') }}",
                    type: "POST",
                    contentType: "application/json",
                    data: JSON.stringify({ package_id: packageId }),
                    success: function (response) {
                        if (response.code === 0) {
                            var items = "";
                            response.data.forEach(function (item) {
                                items += `<p>项目ID: ${item.id}, 内容: ${item.content}</p>`;
                            });
                            resolve(items);
                        } else {
                            showMessage("error", response.message, "message", 3000);
                            reject(response.message);
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        var errorMessage = "获取项目列表失败：" + textStatus + " " + errorThrown;
                        showMessage("error", errorMessage, "message", 3000);
                        reject(errorMessage);
                    }
                });
            });
        }

        function deleteItem(itemId) {
            $.ajax({
                url: "{{ url_for('doctor.delete_item') }}",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({ item_id: itemId }),
                success: function (response) {
                    if (response.code === 0) {
                        showMessage("success", response.message, "message", 3000);
                        queryItem();
                    }
                }
            });
        }

        function queryItem() {
            return new Promise(function (resolve, reject) {
                $.ajax({
                    url: "{{ url_for('doctor.query_item') }}",
                    type: "POST",
                    contentType: "application/json",
                    data: JSON.stringify({}),
                    success: function (response) {
                        if (response.code === 0) {
                            let itemTableBody = $('#item-table-body');
                            itemTableBody.empty();
                            response.data.forEach(({ id, content }) => {
                                itemTableBody.append(`
                                    <tr data-item-id="${id}">
                                        <td>${id}</td>
                                        <td>${content}</td>
                                        <td><button class="operation-btn delete-btn" onclick="deleteItem(${id})">删除</button></td>
                                    </tr>
                                `);
                            });
                            itemTableBody.append(`
                                <tr data-item-id="未分配">
                                    <td>未分配</td>
                                    <td><input type="text" id="new_item_content" name="new_item_content"></td>
                                    <td><button class="operation-btn add-btn" onclick="addItem()">添加</button></td>
                                </tr>
                            `);
                            resolve();
                        } else {
                            reject(response.message);
                        }
                    },
                    error: function (xhr, status, error) {
                        reject('Error fetching package info: ' + error);
                    }
                });
            });
        }

        function deletePackage(packageId) {
            $.ajax({
                url: "{{ url_for('doctor.delete_package') }}",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({ package_id: packageId }),
                success: function (response) {
                    if (response.code === 0) {
                        showMessage("success", response.message, "message", 3000);
                        queryPackages();
                    }
                }
            });
        }

        function queryPackages() {
            $.ajax({
                url: "{{ url_for('doctor.query_package') }}",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({}),
                success: function ({ code, data, message }) {
                    if (code !== 0) {
                        showMessage("error", message || "获取套餐列表失败，请稍后再试。", "message", 3000);
                        return;
                    }

                    let packageTableBody = $('#package-table-body');
                    packageTableBody.empty();
                    data.forEach(({ id, name, description }) => {
                        loadPackageDetails(id).then(function (items) {
                            packageTableBody.append(`
                                <tr data-package-id="${id}">
                                    <td>${id}</td>
                                    <td>${name}</td>
                                    <td>${description}</td>
                                    <td><p>${items}</p></td>
                                    <td><button class="operation-btn delete-btn" onclick="deletePackage(${id})">删除</button></td>
                                </tr>
                            `);
                        }).catch(function (error) {
                            showMessage("error", "Error:" + error, "message", 3000);
                        });
                    });

                    packageTableBody.append(`
                        <tr data-package-id="0">
                            <td>未分配</td>
                            <td><input type="text" id="new_package_name" name="new_package_name"></td>
                            <td><textarea id="new_package_description" name="new_package_description"></textarea></td>
                            <td><input type="text" id="new_package_item_ids" name="new_package_item_ids"></td>
                            <td><button class="operation-btn add-btn" onclick="addPackage()">添加</button></td>
                        </tr>
                    `);

                    // Load details for the first package initially
                    if (data.length > 0) {
                        let firstPackageId = data[0].id;
                        loadPackageDetails(firstPackageId);

                    }
                },
                error: function () {
                    showMessage("error", "网络错误，获取套餐列表失败，请稍后再试。", "message", 3000);
                }
            });
        }

        function addPackage() {
            let name = $('#new_package_name').val();
            let description = $('#new_package_description').val();
            let item_ids = $('#new_package_item_ids').val();
            $.ajax({
                url: "{{ url_for('doctor.add_package') }}",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({
                    name: name,
                    description: description,
                    item_ids: item_ids
                }),
                success: function ({ code, data, message }) {
                    queryPackages();
                }
            });
        }

        function addItem() {
            let content = $('#new_item_content').val();
            $.ajax({
                url: "{{ url_for('doctor.add_item') }}",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({
                    content: content
                }),
                success: function ({ code, data, message }) {
                    queryItem();
                }
            });
        }

        $(document).ready(function () {
            queryPackages();
            queryItem();

            $('#package-table-body').on('click', 'tr', function () {
                let packageId = $(this).data('package-id');
                loadPackageDetails(packageId);

            });
        });
    </script>
</head>

<body>
    <div id="message" class="message-box"></div>

    <hr>
    <h2>预约套餐管理</h2>
    <table id="package-table">
        <thead>
            <tr>
                <th>预约套餐编号</th>
                <th>预约套餐名称</th>
                <th>预约套餐描述</th>
                <th>预约套餐包含项目</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id="package-table-body">
        </tbody>
    </table>

    <hr>
    <h2>预约项目管理</h2>
    <table id="item-table">
        <thead>
            <tr>
                <th>预约项目编号</th>
                <th>预约项目内容</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id="item-table-body">
        </tbody>
    </table>
    <div style="">
        <button style="text-align: center" class="layui-btn layui-btn-normal layui-btn-radius">
            <a href="{{ url_for('doctor.dashboard_doctor_web') }}">返回面板主页</a>
        </button>
    </div>

</body>

</html>
